package com.lxd.property.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;


import org.springframework.web.multipart.MultipartFile;


import com.lxd.cpic.generate.util.reflect.ReflectAgent;
import com.lxd.cpic.generate.util.reflect.ReflectException;

public class ReadExcel<T>{

	private Class<T> persistentClass; 

	/**
	 * 无参构造
	 */
	public ReadExcel(){

	}

	public ReadExcel(Class<T> persistentClass) {     
		this.persistentClass = persistentClass;      
		} 


	public  List<T> getExcelInfo(MultipartFile multipartFile,HttpServletRequest request){
		List<T> list=null;
		File file =null;
		String filepath = uploading(multipartFile, request,file);

		try {
			list = ReflectAgent.getAll(persistentClass,filepath);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ReflectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		deleteFile(filepath);

		return list;
	}


	/**
	 * 上传文件
	 * @param multipartFile
	 * @param request
	 * @return
	 */
	private String  uploading(MultipartFile multipartFile,HttpServletRequest request,File file){
		String path = request.getSession().getServletContext().getRealPath("/WEB-INF/tempfiles");

		String filepath =null;
		if(!multipartFile.isEmpty()){
			filepath= path+"\\"+System.currentTimeMillis()+multipartFile.getOriginalFilename().toLowerCase();
			file = new File(filepath);

			try {
				multipartFile.transferTo(file);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return filepath;
	}


	/**
	 * 删除文件
	 * @param file
	 */
	private void deleteFile(String path){
		File file= new File(path);
		file.delete();
	}


}
